﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using Torimi.Wiki.DataObjects;
using Torimi.Wiki.Interfaces;
using System.Web.Routing;
using System.IO;

namespace Torimi.Wiki.Web
{
	public static class Services
	{
		public static void Initialise()
		{
			Logger.LogInformation("Application Initialisation underway....");

			// Create instances of the services required to run...
			_logger = CreateServiceInstance("LoggingService") as ILogger;
			WikiInstance = CreateServiceInstance("WikiService") as IWiki;
			BackupService = CreateServiceInstance("BackupService") as IBackupService;

			// Register routes for the route table...
			RegisterRoutes();

			// Whilst in development, load the default data...
			Development.LoadDefaultCategories();
			Development.LoadDefaultWikiPages();
		}
		
		private static object CreateServiceInstance(string appSettingName)
		{
			// Get the service type from web.config...
			var serviceTypeName = System.Configuration.ConfigurationManager.AppSettings[appSettingName];

			// Create a type...
			Type t = Type.GetType(serviceTypeName);

			// Create an instance of that type...
			var instance = Activator.CreateInstance(t);

			// Log the event...
			Logger.LogInformation(string.Format("Service: {0} '{1}' created.", appSettingName, t));

			return instance;
		}

		/// <summary>
		/// Registers the routes.
		/// </summary>
		public static void RegisterRoutes()
		{
			// http://msdn.microsoft.com/en-us/library/cc668201.aspx
			RouteTable.Routes.MapPageRoute("WikiPage", "Wiki/{Name}", "~/WikiPage.aspx");
		}

		#region Properties

		/// <summary>
		/// Gets the wiki instance.
		/// </summary>
		public static IWiki WikiInstance { get; private set; }

		/// <summary>
		/// Gets the logger.
		/// </summary>
		public static ILogger Logger 
		{
			get { return _logger; }
		}
		private static ILogger _logger = new Torimi.Wiki.Services.MemoryLogger();

		/// <summary>
		/// Gets the Backup Service.
		/// </summary>
		public static IBackupService BackupService { get; private set; }

		#endregion
	}
}